package com.zxjbyte.yiyi.framework.web.filter;

import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 将输入流内容读取到一个字节数组中，然后对该字节数组进行多次操作
 * @Author zhangxingjia
 * @Date 2023/3/17 20:25
 * @Version: 1.0
 */
public class YiyiHttpServletRequestWrapper extends HttpServletRequestWrapper {

    //没被包装过的HttpServletRequest
    private final HttpServletRequest origRequest;
    // 缓存body
    private byte[] body;

    public YiyiHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.origRequest = request;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (super.getHeader(HttpHeaders.CONTENT_TYPE) == null
                || super.getHeader(HttpHeaders.CONTENT_TYPE).startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
            return super.getInputStream();
        }

        if (body == null) {
            body = ServletXUtil.getBodyBytes(super.getRequest());
        }

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public int available() { //获取当前可从流中读取的字节数
                return body.length;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }


    /**
     * 获取初始request
     *
     * @return HttpServletRequest
     */
    public HttpServletRequest getOrigRequest() {
        return origRequest;
    }

    /**
     * 获取初始request
     *
     * @param request request
     * @return HttpServletRequest
     */
    public static HttpServletRequest getOrigRequest(HttpServletRequest request) {
        if (request instanceof YiyiHttpServletRequestWrapper) {
            return ((YiyiHttpServletRequestWrapper) request).getOrigRequest();
        }
        return request;
    }
}
